from flask import render_template, redirect, url_for, flash, request, current_app
from flask_login import current_user, login_required
from app import db
from app.main import bp
from app.models import User, Skill, Article
from app.main.forms import SearchForm

@bp.route('/')
@bp.route('/index')
def index():
    # 获取最新的5篇文章
    recent_articles = Article.query.order_by(Article.created_at.desc()).limit(5).all()
    # 获取所有技能标签
    skills = Skill.query.all()
    return render_template('main/index.html', title='首页', 
                           recent_articles=recent_articles, skills=skills)

@bp.route('/search', methods=['GET', 'POST'])
def search():
    form = SearchForm()
    results = {'users': [], 'articles': []}
    
    if request.method == 'POST' or request.args.get('q'):
        query = form.q.data or request.args.get('q', '')
        if query:
            # 搜索用户
            users = User.query.filter(User.name.contains(query)).all()
            results['users'] = users
            
            # 搜索文章（标题或内容）
            articles = Article.query.filter(
                (Article.title.contains(query)) | (Article.content.contains(query))
            ).all()
            
            # 通过技能标签搜索文章
            skills = Skill.query.filter(Skill.name.contains(query)).all()
            for skill in skills:
                for article in skill.articles:
                    if article not in articles:  # 避免重复
                        articles.append(article)
            
            results['articles'] = articles
    
    return render_template('main/search.html', title='搜索结果', 
                           form=form, results=results, query=request.args.get('q', ''))